import os
import urllib2, urllib
from tornado.escape import json_encode, json_decode

class SaeFts:
    _app_key = None
    _secret_key = None
    _manageurl = "http://fts.sae.sina.com.cn/SaeSearch_new/IndexManage.php"
    _searchurl = "http://fts.sae.sina.com.cn/SaeSearch_new/Search.php"
    _body = None
    _header = None	
    
    def __init__(self):		
        self._app_key = os.environ.get('ACCESS_KEY', '')	
        self._secret_key = os.environ.get('SECRET_KEY', '')	
    
    def addDoc(self, id, content, groupid = 0, option = {}):	
        post = {}
        params = {}	
        params["cmd"] = "adddoc"
        params["userid"] = self._app_key	
        params["docid"] = int(id)
        params["groupid"] = groupid	
        params.update(option)		
        post["content"] = content
        self._manageurl = self._manageurl+"?"+'&'.join(["%s=%s" % (k, v) for k, v in params.items()])
        f = urllib2.urlopen(self._manageurl,urllib.urlencode(post))
        data = f.read()
        f.close()
        return data
    def search(self, q, sort_filed = "file_long1", sort_mode = "asced", page_size = 20, page_num = 0, option = {}):
		params = {}
		params["userid"] = self._app_key
		params["q"] = q
		params["sortfiled"] = sort_filed
		params["pagestart"] = page_num
		params["pagetotal"] = 1
		params["pagenum"] = page_size
		params["sortmode"] = sort_mode
		params.update(option)
		url = self._searchurl+"?"+"&".join(["%s=%s" % (k,v) for k, v in params.items()])
		f = urllib2.urlopen(url)
		data = json_decode(f.read())
		f.close()
		ret = {}
	
		
		if data["errmsg"] == "success":
			if len(data["result"]) == 0:
				return {"count":0,"result":[]}	
			ret["count"] = int(data["result"]["count"])
			if ret["count"] == 0:
				return None
			ret["data"] = []
			for val in data["result"]["result"]:
				ret["data"].append(int(val["docid"]))
			return ret
		return None

